<template>
  <div class="login-callback">
    <div class="loading-container">
      <div class="loading-spinner" :style="{ borderTopColor: brandColor }"></div>
      <p class="loading-text">{{ message }}</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { githubLoginCallbackApi, qqLoginCallbackApi } from '@/api/auth';
import { useUserStore } from '@/store/modules/user';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const UserStore = useUserStore();
const message = ref('正在处理登录回调...');

// 根据路径判断登录类型
const loginType = computed(() => {
  const path = route.path;
  if (path.includes('/github/')) return 'github';
  if (path.includes('/qq/')) return 'qq';
  return 'unknown';
});

// 根据登录类型配置
const loginConfig = computed(() => {
  switch (loginType.value) {
    case 'github':
      return {
        name: 'GitHub',
        brandColor: '#333',
        stateKey: 'github_login_state',
        callbackApi: githubLoginCallbackApi
      };
    case 'qq':
      return {
        name: 'QQ',
        brandColor: '#12b7f5',
        stateKey: 'qq_login_state',
        callbackApi: qqLoginCallbackApi
      };
    default:
      return null;
  }
});

const brandColor = computed(() => loginConfig.value?.brandColor || '#666');

// 处理第三方登录回调
const handleThirdPartyCallback = async () => {
  const config = loginConfig.value;
  if (!config) {
    message.value = '未知的登录方式';
    setTimeout(() => {
      router.replace('/login');
    }, 2000);
    return;
  }

  try {
    // 获取回调参数
    const code = route.query.code as string;
    const state = route.query.state as string;
    const error = route.query.error as string;
    const errorDescription = route.query.error_description as string;

    console.log(`=== ${config.name}回调调试信息 ===`);
    console.log('当前URL:', window.location.href);
    console.log('回调参数:', { code, state, error, errorDescription });
    console.log('Referer:', document.referrer);
    console.log('用户代理:', navigator.userAgent);
    console.log('时间戳:', new Date().toISOString());
    console.log('==============================');

    // 检查是否是错误回调
    if (error === 'access_denied') {
      message.value = '用户取消了授权';
      setTimeout(() => {
        router.replace('/login');
      }, 2000);
      return;
    }

    if (error) {
      message.value = `授权失败: ${errorDescription || error}`;
      setTimeout(() => {
        router.replace('/login');
      }, 2000);
      return;
    }

    if (!code) {
      message.value = '授权码缺失，登录失败';
      setTimeout(() => {
        router.replace('/login');
      }, 2000);
      return;
    }

    // 验证state参数
    const savedState = localStorage.getItem(config.stateKey);
    if (state && savedState && state !== savedState) {
      message.value = '安全验证失败，请重新登录';
      localStorage.removeItem(config.stateKey);
      setTimeout(() => {
        router.replace('/login');
      }, 2000);
      return;
    }

    // 清除state
    localStorage.removeItem(config.stateKey);

    message.value = `正在验证${config.name}授权信息...`;

    // 调用对应的登录回调API
    const response = await config.callbackApi({
      code,
      state: state || undefined
    });

    console.log(`${config.name}登录响应:`, response);

    if (response?.data?.accessToken) {
      // 设置用户登录信息到Pinia store
      await UserStore.setLoginResult(response.data);

      message.value = `${config.name}登录成功！正在跳转...`;

      // 获取重定向路径，默认跳转到首页
      const redirect = (route.query.redirect as string) || '/';

      // 跳转到目标页面
      setTimeout(() => {
        router.replace(redirect);
      }, 1000);
    } else {
      throw new Error('登录响应数据无效');
    }
  } catch (error: any) {
    console.error(`${config?.name || '第三方'}登录回调处理失败:`, error);

    // 根据不同的错误类型显示不同的提示
    let errorMessage = `${config?.name || '第三方'}登录失败`;

    if (error.response?.status === 400) {
      const errorResponse = error.response?.data?.message || `${config?.name || '第三方'}授权失败`;
      if (errorResponse.includes('用户不存在') || errorResponse.includes('创建用户失败')) {
        errorMessage = `该${config?.name}账号还未绑定账号，请先注册账号再绑定${config?.name}`;
      } else if (errorResponse.includes('账号已删除')) {
        errorMessage = '您的账号已被删除，请联系工作人员！';
      } else if (errorResponse.includes('账号已禁用')) {
        errorMessage = '您的账号已被禁用，请联系工作人员！';
      } else {
        errorMessage = `${config?.name}登录失败: ${errorResponse}`;
      }
    } else if (error.response?.status === 401) {
      errorMessage = `${config?.name}授权已过期，请重新授权`;
    } else if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
      errorMessage = '网络连接失败，请检查网络后重试';
    } else {
      errorMessage = `${config?.name}登录失败: ${error.message || '请重试'}`;
    }

    message.value = errorMessage;

    setTimeout(() => {
      router.replace('/login');
    }, 2000);
  }
};

onMounted(() => {
  handleThirdPartyCallback();
});
</script>

<style lang="scss" scoped>
.login-callback {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

.loading-text {
  font-size: 14px;
  color: #666;
  margin: 0;
  max-width: 300px;
  line-height: 1.5;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
